# -*- coding:utf8 -*-
__author__ = 'Forcs'

from django.conf.urls import url
from django.core.urlresolvers import reverse
from wanbatvcom.http.decorators import require_params
from wanbatvcom.http.whttp import send_error_response_with_message, send_ok_response_with_data
import views
from wancake.resmng.main import resmng
from wancake.auth import encode_password
from django.contrib.sessions.backends.db import SessionStore
import wancake.views as wc_views
from wanbatvcom.settings import SESSION_COOKIE_AGE
import datetime

class AuthService(object):

    @property
    def urls(self):
        urlpatterns = [
            url(r'^login$', self.get_login_view, name="get_login"),
            url(r'^dologin$', self.login, name="do_login"),
            url(r'^dologout$', self.logout, name="do_logout")
        ]
        return urlpatterns

    @require_params(["username", "password"], method="POST")
    def login(self, request):
        body = request.POST
        account = body["username"]
        password = body["password"]

        member = resmng.find_member(account)
        if member:
            password_encoded = encode_password(password)
            if member["password"] == password_encoded:
                # 更新session
                request.session["member_token"] = member["token"]
                session = SessionStore()
                session["member_token"] = member["token"]
                session.set_expiry(SESSION_COOKIE_AGE)
                session.save()
                session_id = session.session_key
                update = {
                    "account": account,
                    "session_id": session_id,
                    "is_active": True
                }
                resmng.update_member(update)
                return send_ok_response_with_data(data={
                    "sessionId": session_id
                })
            else:
                return send_error_response_with_message(message=u'密码错误')
        else:
            return send_error_response_with_message(message=u'查无此人 %s' % account)

    @require_params(["session"])
    def logout(self, request):
        query = request.GET
        session_id = query["session"]
        session = SessionStore(session_key=session_id)
        session.set_expiry(None)

        if "member_token" in session.keys():
            member_token = session.get("member_token", None)
            member = resmng.find_member(token=member_token)
            account = member["account"]
            if member:
                update = {
                    "account": account,
                    "session_id": "",
                    "is_active": False
                }
                resmng.update_member(update)
                return send_ok_response_with_data(data={
                    "account": account
                }, message=u'%s 注销成功' % account)
            else:
                return send_error_response_with_message(message=u'查无此人 %s' % account)
        else:
            return send_error_response_with_message(message=u'session无效')

    def get_login_view(self, request):
        query = request.GET
        next_url = None
        try:
            next_url = query["next"]
        except KeyError:
            pass

        context = {
            "next_url": next_url if next_url else reverse(wc_views.index)
        }

        return views.get_login(request, context=context)

auth = AuthService()
